package projectnfc.receiver.hro;

import java.util.concurrent.ExecutionException;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class PostServerActivity extends Activity implements OnClickListener {
	private EditText nfcdeviceserial, serverIP, studentDocentCode;
	private Button bVerstuur;
	private TextView tvAdd,tvNFCDeviceSerial,tvStudentDocentCode,tvServerIP;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.postserver);

		serverIP = (EditText) findViewById(R.id.etServerIP);
		serverIP.setTextColor(Color.BLUE);
		
		studentDocentCode = (EditText) findViewById(R.id.etStudentDocent);
		studentDocentCode.setTextColor(Color.BLUE);
		
		bVerstuur = (Button) findViewById(R.id.bVerstuurData);
		bVerstuur.setTextColor(Color.RED);
		
		tvAdd = (TextView) findViewById(R.id.tvAdd);
		tvAdd.setTextColor(Color.RED);
		
		nfcdeviceserial = (EditText) findViewById(R.id.etNFCDeviceSerial);
		nfcdeviceserial.setTextColor(Color.BLUE);
		
		tvNFCDeviceSerial = (TextView) findViewById(R.id.tvNFCDeviceSerial);
		tvNFCDeviceSerial.setTextColor(Color.RED);
		
		tvStudentDocentCode = (TextView) findViewById(R.id.tvStudentDocentCode);
		tvStudentDocentCode.setTextColor(Color.RED);
		
		tvServerIP = (TextView) findViewById(R.id.tvServerIP);
		tvServerIP.setTextColor(Color.RED);
		
		// Sends data when user clicks on button
		bVerstuur.setOnClickListener(this);

		// Checks if application is started from a tag
		Intent intent = getIntent();
		if (intent.getType() != null && intent.getType().equals(MimeType.NFC)) {
			Parcelable[] rawMsgs = getIntent().getParcelableArrayExtra(
					NfcAdapter.EXTRA_NDEF_MESSAGES);
			NdefMessage msg = (NdefMessage) rawMsgs[0];
			NdefRecord rRecord = msg.getRecords()[0];
			String consoleName = new String(rRecord.getPayload());
			displayRead(consoleName);
		}
	}

	private void displayRead(String output) {
		studentDocentCode.setText(output);
	}

	@Override
	public void onClick(View v) {
		NFCPostToServer server = new NFCPostToServer(serverIP.getText()
				.toString());
		server.execute(studentDocentCode.getText().toString(), nfcdeviceserial.getText()
				.toString());
		try {
			if (server.get()) {
				tvAdd.setText("Post result: Succes");
			} else {
				tvAdd.setText("Post result: Exception was thrown.");
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}

	}

}
